package com.example.android_file_manger;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Stack;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.example.android_file_manger.adapter.LocalFileAdapter;
import com.example.android_file_manger.common.AppManager;
import com.example.android_file_manger.common.CustomDialog;
import com.example.android_file_manger.common.FileUtil;
import com.example.android_file_manger.myview.MyButtion;
import com.op.teachingliteapp.R;
import com.op.teachingliteapp.common.Common;
import com.op.teachingliteapp.fragment.smartpan.SmartPanFragment;
import com.op.teachingliteapp.util.SharedPreferenceUtil;

public class MainActivity extends BaseActivity implements OnClickListener {

	public static String filePath;
	public static String fileName, storageState;
	private int check = 0;// 创建文件的标志
	private LocalFileAdapter adapter;
	private Map<String, String> map = null;// 这个用来保存复制和粘贴的路径
	private TextView titleView;
	private File root;
	private ListView listView;

	private List<File> list;
	private View view;

	// path的堆栈
	private static Stack<String> pathStack;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		view = LayoutInflater.from(MainActivity.this).inflate(R.layout.local_file_dialog, null);
		setContentView(view);
		titleView = (TextView) findViewById(R.id.local_File_title);
		ImageView pictureShow = (ImageView) findViewById(R.id.picture_show);
		storageState = Environment.getExternalStorageState();

		if (storageState.equals(Environment.MEDIA_MOUNTED)) {
			root = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
		} else {
			finish();
		}

		initView();

	}

	/**
	 * 查询调用方法
	 */
	public void searchData(String path) {
		searchViewData(path);
	}

	/**
	 * 查询view的数据
	 */
	public void searchViewData(final String path) {

		putAsyncTask(new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {

				try {
					list = FileUtil.getFileListByPath(path);
				} catch (Exception e) {
					return false;
				}

				return true;
			}

			@Override
			protected void onPostExecute(Boolean result) {
				super.onPostExecute(result);

				if (result) {

					adapter.setFiles(list);

					adapter.setSelectedPosition(-1);

					adapter.notifyDataSetChanged();

				} else {
					Toast.makeText(MainActivity.this, "查询失败", Toast.LENGTH_LONG).show();
				}
			}
		});
	}

	/**
	 * 初始化视图
	 */
	private void initView() {

		LinearLayout layout = (LinearLayout) findViewById(R.id.local_File_lin);

		listView = (ListView) findViewById(R.id.local_File_drawer);

		adapter = new LocalFileAdapter(this, list);

		listView.setAdapter(adapter);

		map = new HashMap<String, String>();

		listView.setOnItemClickListener(new DrawerItemClickListener());
		registerForContextMenu(listView);// 注册一个上下文菜单

		ImageButton returnBtn = (ImageButton) findViewById(R.id.local_File_return_btn);

		returnBtn.setOnClickListener(this);

		MyButtion addButtion = (MyButtion) findViewById(R.id.myButtion1);
		MyButtion searchButtion = (MyButtion) findViewById(R.id.myButtion2);
		MyButtion menuButtion = (MyButtion) findViewById(R.id.myButtion3);
		addButtion.setOnClickListener(this);
		searchButtion.setOnClickListener(this);
		menuButtion.setOnClickListener(this);
		searchData(root.getAbsolutePath());
		addPath(root.getAbsolutePath());

	}

	/*
	 * 创建一个上下文菜单
	 */
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub
		getMenuInflater().inflate(R.menu.file_item, menu);

		super.onCreateContextMenu(menu, v, menuInfo);
	}

	/*
	 * 上下文菜单选项
	 */
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		final int position = info.position;
		final List<File> list = adapter.getFiles();// 得到文件的list
		String path = list.get(position).getPath();
		System.out.println("-----" + path + "-------");
		switch (item.getItemId()) {
		case R.id.copy:
			// 复制目录
			System.out.println("复制目录");
			String fromPath = list.get(position).getPath();
			System.out.println(list.get(position).getPath());
			map.put("fromPath", fromPath);
			System.out.println("最" + getLastPath());

			System.out.println(map.get("fromPath"));
			String name = map.get("fromPath").substring(getLastPath().length() + 1, map.get("fromPath").length());
			map.put("name", name);
			System.out.println(name);
			break;
		case R.id.stick:
			System.out.println("粘贴");
			if (!map.isEmpty()) {
				File file = new File(map.get("fromPath"));
				if (file.isFile()) {
					FileUtil.copyFile(file, map.get("name"), list.get(position));
					File tFile = new File(list.get(position), map.get("name"));
					if (tFile != null && tFile.exists()) {
						Toast.makeText(MainActivity.this, "复制文件成功", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(MainActivity.this, "复制文件失败", Toast.LENGTH_SHORT).show();
					}
				} else {
					FileUtil.copyFolder(file, new File(list.get(position), map.get("name")));
					File dFile = new File(list.get(position), map.get("name"));
					if (dFile != null && dFile.exists()) {
						Toast.makeText(MainActivity.this, "复制目录成功", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(MainActivity.this, "复制目录失败", Toast.LENGTH_SHORT).show();
					}
				}
				map.clear();// 清空
				searchData(getLastPath());
			} else {
				Toast.makeText(MainActivity.this, "还没有选中要复制的文件或目录", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.cancel:
			if (!map.isEmpty()) {
				map.clear();
				Toast.makeText(MainActivity.this, "已取消", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(MainActivity.this, "没有复制的目录或文件", Toast.LENGTH_SHORT).show();
			}
			break;
		case R.id.del:
			final CustomDialog customDialog = new CustomDialog(MainActivity.this, getCurrentFocus());
			customDialog.setTitle("提示");
			customDialog.setMessage("确定删除?");
			customDialog.setPositiveButton("确定", new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					customDialog.dismiss();
					File dir = list.get(position);
					if (dir.isFile()) {
						dir.delete();
					} else {
						FileUtil.deleteDir(list.get(position));
					}
					if (dir == null || !dir.exists()) {
						Toast.makeText(MainActivity.this, "删除成功", Toast.LENGTH_SHORT).show();
						searchData(titleView.getText().toString());
					} else {
						Toast.makeText(MainActivity.this, "删除失败", Toast.LENGTH_SHORT).show();
					}
				}
			});
			customDialog.setNegativeButton("取消", new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					customDialog.dismiss();
				}
			});
			customDialog.show();
			break;
		case R.id.mod:
			// 重命名
			AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
			builder.setTitle("提示对话框");
			View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.mydialog, null);
			builder.setView(view);
			final EditText toEditText = (EditText) view.findViewById(R.id.rename_edit);
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					if (FileUtil.renameFile(list.get(position), getLastPath(), toEditText.getText().toString())) {
						Toast.makeText(MainActivity.this, "重命名成功", Toast.LENGTH_SHORT).show();
						searchData(getLastPath());
					}
					{
						Toast.makeText(MainActivity.this, "重命名失败", Toast.LENGTH_SHORT).show();
					}
					dialog.dismiss();
				}
			});
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.dismiss();
				}
			});
			builder.create().show();

			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	/**
	 * 添加路径到堆栈
	 * 
	 * @param path
	 */
	public void addPath(String path) {

		if (pathStack == null) {
			pathStack = new Stack<String>();
		}

		pathStack.add(path);
	}

	/**
	 * 获取堆栈最上层的路径
	 * 
	 * @return
	 */
	public static String getLastPath() {
		return pathStack.lastElement();
	}

	/**
	 * 移除堆栈最上层路径
	 */
	public void removeLastPath() {
		pathStack.remove(getLastPath());
	}

	private class DrawerItemClickListener implements ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

			adapter.setSelectedPosition(position);
			Map<String, Object> prefsMap = new HashMap<String, Object>();
			prefsMap.put(Common.Prefs.FILE_PATH, adapter.getPath(position));
			SharedPreferenceUtil.saveData(MainActivity.this, prefsMap);
			titleView.setText(adapter.getPath(position));
			selectItem(position);
		}
	}

	private void selectItem(int position) {

		filePath = adapter.getFiles().get(position).getAbsolutePath();

		fileName = adapter.getFiles().get(position).getName();

		if (adapter.getFiles().get(position).isDirectory()) {
			searchData(filePath);
			addPath(filePath);
		} else if (adapter.getFiles().get(position).isFile()) {
			// ResourceDetailsFragment resourceDetailsFragment = new
			// ResourceDetailsFragment();
			// Bundle bundle = new Bundle();
			// bundle.putString("filePath", filePath);
			// bundle.putString("fileName",fileN);
			// resourceDetailsFragment.setArguments(bundle);
			// 判断是否为文件
			finish();
		} else {
			finish();
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.local_File_return_btn:
			if (getLastPath().equals(root.getAbsolutePath())) {
				return;
			}
			removeLastPath();
			searchData(getLastPath());

			break;
		case R.id.myButtion1:
			System.out.println("------添加-------");
			AlertDialog alertDialog = oncreateAlertDialog();
			alertDialog.show();
			break;
		case R.id.myButtion2:
			System.out.println("-------搜索-------");
			break;
		case R.id.myButtion3:
			System.out.println("-------菜单--------");
			break;
		default:
			break;
		}

	}

	public AlertDialog oncreateAlertDialog() {
		AlertDialog.Builder builder = new Builder(MainActivity.this);
		builder.setTitle("提示对话框");
		final View dialogView = LayoutInflater.from(MainActivity.this).inflate(R.layout.myadd_dialog, null);
		builder.setView(dialogView);
		final EditText toText = (EditText) dialogView.findViewById(R.id.add_file_dir);
		RadioGroup radioGroup = (RadioGroup) dialogView.findViewById(R.id.radioGroup1);
		radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				// TODO Auto-generated method stub
				switch (checkedId) {
				case R.id.file:
					check = 0;
					System.out.println(check);
					break;

				case R.id.dir:
					check = 1;
					System.out.println(check);
					break;
				}
			}
		});

		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if (!toText.getText().toString().equals("") && toText.getText().toString() != null) {
					// 创建目录或文件的方法
					FileUtil.createDirorFile(getLastPath(), toText.getText().toString(), MainActivity.this, check);
				}
				searchData(getLastPath());
				dialog.dismiss();
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.dismiss();
			}
		});
		return builder.create();
	}

	@Override
	protected void onDestroy() {
		Log.i("MainActivity", "" + "onDestroy");
		AppManager.getAppManager().finishActivity(this);
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		Log.i("MainActivity", "" + "onResume");
		super.onResume();
	}

	@Override
	protected void onStop() {
		SharedPreferences preferences = this.getSharedPreferences("TeachingLite", Context.MODE_PRIVATE);
		String filePath = preferences.getString(Common.Prefs.FILE_PATH, Environment.getExternalStorageState());
		SmartPanFragment.mySmartPanFileChoose.setText(filePath);
		Log.i("MainActivity", "" + "onStop");
		super.onStop();
	}
	// @Override
	// public boolean onKeyDown(int keyCode, KeyEvent event) {
	// // TODO Auto-generated method stub
	// if (keyCode == KeyEvent.KEYCODE_BACK) {
	// final CustomDialog customDialog = new CustomDialog(
	// MainActivity.this, view);
	// customDialog.setTitle("提示");
	// customDialog.setMessage("确定退出吗?");
	// customDialog.setPositiveButton("确定", new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// customDialog.dismiss();
	// AppManager.getAppManager().AppExit(MainActivity.this);
	// }
	// });
	// customDialog.setNegativeButton("取消", new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// // TODO Auto-generated method stub
	// customDialog.dismiss();
	// }
	// });
	// customDialog.show();
	//
	// }
	// return super.onKeyDown(keyCode, event);
	// }

}
